package com.hjy.search.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class main3 {
    private static ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务一开始");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务一结束");
            return "hello1";
        }, threadPool);

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务二开始");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务二结束");
            return "hello2";
        }, threadPool);

        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务三开始");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务三结束");
            return "hello3";
        }, threadPool);

        // 和 get 的效果一样
        CompletableFuture<Object> future = CompletableFuture.anyOf(future1, future2, future3);

        // 等待三个任务某一个完成再进行下一步
        Object join = future.join();
        System.out.println("join = " + join);

    }
/**
 任务一开始
 任务二开始
 任务三开始
 任务三结束
 join = hello3
 任务二结束
 任务一结束
 */
}
